<?php
class Core_Common_Controllers_Actions_Helpers_Authentication extends Zend_Controller_Action_Helper_Abstract {
	private $_user;
	private $_auth;
	
	public function __construct() {
		$auth = Zend_Auth::getInstance();
		$this->_auth = $auth;
		$this->_user = $auth->getIdentity();
	}
	
	/** 
	 * Reload profil after authentication elements had been changed
	 * like password or login
	 */
	public function reload() {
		$user = Core_Business_User::getById($this->_user->Id);
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
		try {
			$auth->authenticate($this->_getAuthAdapter(array("username"=>$user->Email,"password"=>$user->Password)));
		}
		catch(Exception $e) {
			$auth->clearIdentity();
			$this->getRequest()->_redirect('index');
		}
	}
	
	public function loggedout() {
		$this->_auth->clearIdentity();
		$this->getRequest()->_redirect('index');
	}
	
	protected function _getAuthAdapter($formData) {
		$dbAdapter = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('db');
		
		$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
		$authAdapter->setTableName('users')
					->setIdentityColumn('email')
					->setCredentialColumn('password')
					->setCredentialTreatment('SHA1(?)');
		$config = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getOptions();
		//$salt = $config->auth->salt;
		$salt='';
		$password = $salt.$formData['password'];
		$authAdapter->setIdentity($formData['username']);
		$authAdapter->setCredential($password);
		
		return $authAdapter;
	}

}